<template>
  <div class="app-container">
    <ThePageHead>请假统计（管）</ThePageHead>
    <TheForm label-width="80px" @fetchData="getList" style="margin-left:10px;">
      <template v-slot:gForm>
        <el-form-item label="统计日从">
          <TheDateTime
            type="daterange"
            :startdate.sync="listQuery.params.startdate"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :enddate.sync="listQuery.params.enddate" />
        </el-form-item>
        <el-form-item label="请假人">
          <el-input v-model="listQuery.params.creater" clearable placeholder="请输入姓名"
                    style="width: 175px; height:28px; "/>
        </el-form-item>
      </template>
      <template v-slot:gFormFoot>
      </template>
    </TheForm>


    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      :render-header="labelHead"
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column type="index" label="序号" width="50px" align="center"/>
      <el-table-column label="请假人" align="center">
        <template slot-scope="{row}">
          <span>{{ row.fullname }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="getholidaytypestr(item)" v-for="(item, index) in header" :key="item" align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row[item] > 0">
            {{ scope.row[item] }}
          </el-tag>
          <span v-else>{{ scope.row[item] }}</span>
          <!--<span v-for="(item2,index2) in scope.row.transportNumByDistance" v-if="index2 == index">
            {{ scope.row.transportNumByDistance[index2].transportNum }} </span>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList" align="center"/>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" style="padding: 40px;">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="160px"
               style="width: 90%;">
        <el-form-item label="请假人：" prop="creater">
          <el-input v-model="temp.creater" disabled style="width:200px;"/>
        </el-form-item>
        <el-form-item label="假期类型：" prop="applytype">
          <el-select v-model="temp.applytype" width="200px" disabled placeholder="请选择假期类型">
            <el-option
              v-for="h in holidaytypes"
              :key="h.key"
              :label="h.display_name"
              :value="h.key"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="请假原因：" prop="applyformemo">
          <el-input v-model="temp.applyformemo" disabled style="width:100%;"/>
        </el-form-item>

        <el-form-item label="请假日：" prop="holidaydatestr">
          <el-input v-model="temp.holidaydatestr" disabled style="width:100%;"/>
        </el-form-item>
        <el-form-item label="审批结果：" prop="checkstatus">
          <el-select v-model="temp.checkstatus" placeholder="请选择审批结果">
            <el-option
              v-for="h in checkstatus"
              :key="h.key"
              :label="h.display_name"
              :value="h.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核意见：" prop="checkmemo">
          <el-input v-model="temp.checkmemo" style="width:100%;"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="checkapplyfor()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getstatistical} from '@/api/holiday'
  import waves from '@/directive/waves' // waves directive
  import {parseTime} from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  /*
  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})
  */
  export default {
    name: 'statist',
    components: {Pagination},
    directives: {waves},
    filters: {
      statusFilter(status) {
        if (status == null || status === '')
          return 'info'

        const statusMap = {
          ok: 'success',
          fail: 'danger'
        }

        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        header: [],
        listQuery: {
          page: 1,
          limit: 20,
          params: {
            creater: "",
            startdate: this.getlastmonthfirstday(),
            enddate: this.getlastmonthlastday()
          },
        },
        textMap: {
          update: '审核休假申请',
          create: '申请休假'
        },
        holidaytypes: [
          {key: 'adjust', display_name: '调休'},
          {key: 'paid', display_name: '带薪假'},
          {key: 'affairs', display_name: '事假'},
          {key: 'sick', display_name: '病假'}
        ],
        checkstatus: [
          {key: 'ok', display_name: '通过'},
          {key: 'fail', display_name: '不通过'}
        ],
        dialogFormVisible: false,
        dialogStatus: '',
        dialogPvVisible: false,
        pvData: [],
        temp: {
          applyforid: '',
          applyformemo: '',
          applytype: '',
          holidaydates: [],
          holidaydatestr: '',
          checkstatus: '',
          checkmemo: ''
        },
        rules: {
          checkstatus: [{required: true, message: '审核结果不能为空！', trigger: 'change'}]
        }/*,
      //importanceOptions: [1, 2, 3],
      //calendarTypeOptions,
      //sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      //statusOptions: ['published', 'draft', 'deleted'],
      //showReviewer: false,
      downloadLoading: false*/
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getlastmonthfirstday(){
        let firstdate = new Date(new Date().getFullYear(), new Date().getMonth()-1, 1);
        return parseTime(firstdate, '{y}-{m}-{d}');
      },
      getlastmonthlastday(){
        let date = new Date();
        let day = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
        let enddate = new Date(new Date().getFullYear(), new Date().getMonth()-1, day);
        return parseTime(enddate, '{y}-{m}-{d}');
      },
      labelHead(h, {column, index}) { //动态表头渲染
        //let l = column.label.length;
        //let f = 12; //每个字大小,其实是每个字的比例值,大概会比字体大小打差不多大
        //column.minWidth = f * l; //字大小乘个数即长度 ,注意不要加px像素，这里minWidth只是一个比例值，不是真正的长度
        //然后将列标题放在一个div块中，注意块的宽度一定要100%，否则表格显示不完全
        return h('span', {class: 'table-head', style: {width: '100%'}}, [column.label])
      },
      getcheckstatusstr(key) {
        let h = this.checkstatus.find(p => p.key == key)
        return h.display_name
      },
      getholidaytypestr(key) {
        let h = this.holidaytypes.find(p => p.key == key)
        return h.display_name
      },
      getList() {
        if(this.listQuery.params.startdate === '' ||
          this.listQuery.params.enddate === ''){
          this.$notify({
            title: 'Warning',
            message: '统计日不能为空！',
            type: 'warning',
            duration: 2000
          })
          return;
        }
        this.listLoading = true
        getstatistical(this.listQuery).then(response => {
          this.list = response.data.data
          this.header = response.data.holtypes;
          this.total = response.page.count

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1000)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      checkapplyfor() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {

          }
        })
      }
      /*,

      handleModifyStatus(row, status) {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },



      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            updateArticle(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },

      handleFetchPv(pv) {
        fetchPv(pv).then(response => {
          this.pvData = response.data.pvData
          this.dialogPvVisible = true
        })
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: 'table-list'
          })
          this.downloadLoading = false
        })
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }

      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }*/
    }
  }
</script>
<style scoped lang="scss">
  .el-form-item label:after {
    content: "";
    display: inline-block;
    width: 100%;
  }

  .el-form-item__label {
    text-align: justify;
    height: 50px;
  }

  .el-form-item.is-required .el-form-item__label:before {
    content: none !important;
  }

  .innerDate {
    width: 100%;
    height: 100%;
  }
</style>
